package com.lunago.agent.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.lunago.agent.constant.HttpConsts;
import com.lunago.agent.constant.JsonResult;
import com.lunago.agent.constant.ServiceCode;
import com.lunago.agent.jwt.JwtPayLoad;
import com.lunago.agent.jwt.JwtTokenUtil;
import com.lunago.agent.service.AuthService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * 认证相关service实现类
 *
 * @author xuyuxiang
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Override
    public String getTokenFromRequest(HttpServletRequest request) {
        String authToken = request.getHeader(HttpConsts.HEADER_AUTHORIZATION);
        if (ObjectUtil.isEmpty(authToken)) {
            return null;
        } else {
            //token不是以Bearer打头，则响应回格式不正确
            if (!authToken.startsWith(HttpConsts.TOKEN_TYPE_BEARER)) {
                String message = "非法访问，Token格式不正确！";
                JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
                return JSON.toJSONString(jsonResult);
            }
            try {
                authToken = authToken.substring(HttpConsts.TOKEN_TYPE_BEARER.length() + 1);
            } catch (StringIndexOutOfBoundsException e) {
                String message = "非法访问，Token解析失败！";
                JsonResult jsonResult = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);
                return JSON.toJSONString(jsonResult);
            }
        }

        return authToken;
    }

    @Override
    public void setSpringSecurityContextAuthentication(JwtPayLoad jwtPayLoad) {
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(jwtPayLoad,null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    @Override
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    @Override
    public void checkToken(String token) {
        //校验token是否正确
        Boolean tokenCorrect = JwtTokenUtil.checkToken(token);
        if (!tokenCorrect) {
            throw new RuntimeException("JWT验证失败");
        }

        //校验token是否失效
        Boolean tokenExpired = JwtTokenUtil.isTokenExpired(token);
        if (tokenExpired) {
            throw new RuntimeException("token已失效");
        }
    }

}